__all__ = (
    'ChineseCharDataset',
)

from typing import Tuple, Dict, Set, List


def get_table(char_table: str) -> Tuple[Dict[str, Set[str]], Dict[str, Set[str]]]:
    chn_to_pinyin, pinyin_to_chn = {}, {}

    char_and_pinyins = char_table.strip().split('\n')
    for char_and_pinyin in char_and_pinyins:
        split_result = char_and_pinyin.split(' ')
        pinyin = split_result[0]
        chns = split_result[1:]

        pinyin_to_chn[pinyin] = set(chns)
        for chn in chns:
            s = chn_to_pinyin.get(chn, set())
            s.add(pinyin)
            chn_to_pinyin[chn] = s

    return chn_to_pinyin, pinyin_to_chn


class ChineseCharDataset:
    """汉字——拼音数据集"""

    def __init__(self, *, char_table: str):
        self.chn_to_pinyin, self.pinyin_to_chn = get_table(char_table)

    def is_chn_in_table(self, chn_char: str) -> bool:
        return chn_char in self.chn_to_pinyin

    def is_pinyin_in_table(self, pinyin: str) -> bool:
        return pinyin in self.pinyin_to_chn

    def get_pinyins_of_chn(self, chn_char: str) -> List[str]:
        return list(self.chn_to_pinyin[chn_char])

    def get_chns_of_pinyin(self, pinyin: str) -> List[str]:
        return list(self.pinyin_to_chn[pinyin])

    def can_chn_read_as_pinyin(self, chn: str, pinyin: str) -> bool:
        pinyin_set = self.chn_to_pinyin[chn]
        return pinyin in pinyin_set
